#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Predesys Server - User Interface - Service permissions management 
@version: 0.2.5
@license: GPL 3.0 (see "license" file)
@author: Jose A. Jimenez
@contact: jajimc@gmail.com"""

import sys
sys.dont_write_bytecode = True
import os
import os.path
DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.path.join(DIR, "../core"))
import security
import exceptions
import usage
import tools
import servicepermissions

def manageArgs(argc, argv):
    """Manages command line input.
    @param argc: Command line argument count
    @type argc: C{int}
    @param argv: Command line input data
    @type argv: C{list}"""
    if argc == 3 and sys.argv[2] == "list":
        print_permission_list()
    elif argc == 5 and sys.argv[2] == "data":
        print_permission_data(argv)
    elif argc == 3 and sys.argv[2] == "add":
        add_permission_interactively()
    elif argc == 7 and sys.argv[2] == "add":
         add_permission(sys.argv)
    elif argc == 3 and sys.argv[2] == "mod":
        modify_permission_interactively()
    elif argc == 11 and sys.argv[2] == "mod":
        modify_permission(sys.argv)
    elif argc == 7 and sys.argv[2] == "del":
        delete_permission(sys.argv, True)
    elif argc == 8 and sys.argv[2] == "del" and sys.argv[3] == "-f":
        delete_permission(sys.argv, False)
    elif argc == 5 and sys.argv[2] == "del" and sys.argv[3] == "-sid":
        delete_permissions_by_service(sys.argv, True)
    elif argc == 6 and sys.argv[2] == "del" and sys.argv[3] == "-f" and sys.argv[4] == "-sid":
        delete_permissions_by_service(sys.argv, False)
    elif argc == 5 and sys.argv[2] == "del" and sys.argv[3] == "-gid":
        delete_permissions_by_group(sys.argv, True)
    elif argc == 6 and sys.argv[2] == "del" and sys.argv[3] == "-f" and sys.argv[4] == "-gid":
        delete_permissions_by_group(sys.argv, False)
    else:
        print usage.get_usage()
        
def print_permission_list():
    """Prints every service permission."""
    permissionList = servicepermissions.get_permissions()
    for permission in permissionList:
        print "SERVICE ID: %s - USER GROUP ID: %s" % (permission[0], permission[1])
        
def print_permission_data(argv):
    """Prints all fields of a service permission.
    @param argv: Command line input data
    @type argv: C{list}"""
    serviceId = tools.get_parameter_value(argv, "sid")
    if serviceId == None:
        userGroupId = tools.get_parameter_value(argv, "gid")
        if userGroupId == None:
            raise exceptions.Exception("Service ID/user group ID not valid or not specified")
    
    if serviceId != None:
        # Get service groups
        data = servicepermissions.get_service_user_groups(serviceId)
    else:
        # Get group's services
        data = servicepermissions.get_user_group_services(userGroupId)
        
    for item in data:
        print item
        
def add_permission_interactively():
    """Adds a new service permission prompting for every field in the command line."""
    security.check_root()
    
    ok = False
    while (not ok):
        serviceId = raw_input("Service ID: ")
        ok = (serviceId != None and serviceId != "")
        if not ok: print "Data not valid, try again"
        
    ok = False
    while (not ok):
        userGroupId = raw_input("User group ID: ")
        ok = (userGroupId != None and userGroupId != "")
        if not ok: print "Data not valid, try again"
    
    servicepermissions.add_permission(serviceId, userGroupId)
    print "Service permission added successfully"
    
def add_permission(argv):
    """Adds a new service permission.
    @param argv: Command line input data
    @type argv: C{list}"""
    security.check_root()
    
    serviceId = tools.get_parameter_value(argv, "sid")
    if serviceId == None or serviceId == "": raise exceptions.Exception("Service ID not valid or not specified")
    
    userGroupId = tools.get_parameter_value(argv, "gid")
    if userGroupId == None or userGroupId == "": raise exceptions.Exception("User group ID not valid or not specified")
    
    servicepermissions.add_permission(serviceId, userGroupId)
    print "Service permission added successfully"
    
def modify_permission_interactively():
    """Modifies an existing service permission prompting for every field in the command line."""
    security.check_root()
    
    ok = False
    while (not ok):
        oldServiceId = raw_input("Old service ID: ")
        ok = (oldServiceId != None and oldServiceId != "")
        if not ok: print "Data not valid, try again"

    ok = False
    while (not ok):
        oldUserGroupId = raw_input("Old user group ID: ")
        ok = (oldUserGroupId != None and oldUserGroupId != "")
        if not ok: print "Data not valid, try again"
        
    ok = False
    while (not ok):
        newServiceId = raw_input("New service ID: ")
        ok = (newServiceId != None and newServiceId != "")
        if not ok: print "Data not valid, try again"

    ok = False
    while (not ok):
        newUserGroupId = raw_input("New user group ID: ")
        ok = (newUserGroupId != None and newUserGroupId != "")
        if not ok: print "Data not valid, try again"

    servicepermissions.modify_permission(oldServiceId, oldUserGroupId, newServiceId, newUserGroupId)
    print "Service permission modified successfully"
    
def modify_permission(argv):
    """Modifies an existing service permission.
    @param argv: Command line input data
    @type argv: C{list}"""
    security.check_root()
    
    oldServiceId = tools.get_parameter_value(argv, "osid")
    if oldServiceId == None or oldServiceId == "": raise exceptions.Exception("Old service ID not valid or not specified")
    
    oldUserGroupId = tools.get_parameter_value(argv, "ogid")
    if oldUserGroupId == None or oldUserGroupId: raise exceptions.Exception("Old user group ID not valid or not specified")
    
    newServiceId = tools.get_parameter_value(argv, "nsid")
    if newServiceId == None or newServiceId == "": raise exceptions.Exception("New service ID not valid or not specified")
    
    newUserGroupId = tools.get_parameter_value(argv, "ngid")
    if newUserGroupId == None or newUserGroupId == "": raise exceptions.Exception("New user group ID not valid or not specified")
        
    servicepermissions.modify_permission(oldServiceId, oldUserGroupId, newServiceId, newUserGroupId)
    print "Service permission modified successfully"
    
def delete_permission(argv, confirm):
    """Deletes an existing service permission.
    @param argv: Command line input data
    @type argv: C{list}
    @param confirm: Determines if UI must prompt the user a confirmation.
    @type confirm: C{bool}"""
    security.check_root()
    
    serviceId = tools.get_parameter_value(argv, "sid")
    if serviceId == None or serviceId == "": raise exceptions.Exception("Service ID not valid or not specified")
    
    userGroupId = tools.get_parameter_value(argv, "gid")
    if userGroupId == None or userGroupId == "": raise exceptions.Exception("User group ID not valid or not specified")
    
    if confirm:
        ok = False
        while (not ok):
            response = raw_input("Are you sure you want to delete permission ('%s', '%s')? [y/n]: " % (serviceId, userGroupId))
            response = response.lower()
            ok = (response != None and response != "" and (response == "y" or response == "n"))
            if not ok: print "Answer not valid"
        if response == "n": 
            exit(0)
            
    servicepermissions.delete_permission(serviceId, userGroupId)
    print "Permission deleted successfully"
    
def delete_permissions_by_service(argv, confirm):
    """Deletes all existing service permissions of a given service.
    @param argv: Command line input data
    @type argv: C{list}
    @param confirm: Determines if UI must prompt the user a confirmation.
    @type confirm: C{bool}"""
    security.check_root()
    
    serviceId = tools.get_parameter_value(argv, "sid")
    if serviceId == None or serviceId == "": raise exceptions.Exception("Service ID not valid or not specified")
    
    if confirm:
        ok = False
        while (not ok):
            response = raw_input("Are you sure you want to delete permissions of service '%s'? [y/n]: " % serviceId)
            response = response.lower()
            ok = (response != None and response != "" and (response == "y" or response == "n"))
            if not ok: print "Answer not valid"
        if response == "n": 
            exit(0)
            
    servicepermissions.delete_permissions_by_service(serviceId)
    print "Permissions deleted successfully"

def delete_permissions_by_group(argv, confirm):
    """Deletes all existing service permissions of a given user group.
    @param argv: Command line input data
    @type argv: C{list}
    @param confirm: Determines if UI must prompt the user a confirmation.
    @type confirm: C{bool}"""
    security.check_root()
    
    userGroupId = tools.get_parameter_value(argv, "gid")
    if userGroupId == None or userGroupId: raise exceptions.Exception("User group ID not valid or not specified")
    
    if confirm:
        ok = False
        while (not ok):
            response = raw_input("Are you sure you want to delete permissions of user group '%s'? [y/n]: " % userGroupId)
            response = response.lower()
            ok = (response != None and response != "" and (response == "y" or response == "n"))
            if not ok: print "Answer not valid"
        if response == "n": 
            exit(0)
            
    servicepermissions.delete_permissions_by_user_group(userGroupId)
    print "Permissions deleted successfully"
